﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace DataLibrary.Utility
{
    public class DataTableHelper
    {
        public static DataTable DataTableSelectTop(int TopItem, DataTable oDT)
        {
            if (oDT.Rows.Count <= TopItem)
                return oDT;

            DataTable NewTable = oDT.Clone();
            DataRow[] rows = oDT.Select(" 1=1 ");
            for (int i = 0; i < TopItem; i++)
            {
                NewTable.ImportRow((DataRow)rows[i]);
            }
            return NewTable;
        }


        public List<T> ConvertToList<T>(DataTable dataTable) where T : new()
        {
            List<T> list = new List<T>();

            foreach (DataRow row in dataTable.Rows)
            {
                T item = new T();

                foreach (DataColumn col in dataTable.Columns)
                {
                    string propertyName = col.ColumnName;
                    object propertyValue = row[col];

                    SetProperty(item, propertyName, propertyValue);
                }

                list.Add(item);
            }

            return list;
        }

        private void SetProperty<T>(T item, string propertyName, object propertyValue) where T : new()
        {
            var property = typeof(T).GetProperty(propertyName);
            if (property != null && property.CanWrite)
            {
                Type propertyType = property.PropertyType;
                object value = Convert.ChangeType(propertyValue, propertyType);
                property.SetValue(item, value);
            }
        }
    }



}
